package com.springbootdemo.shixundemo.Controller;

/**
 * @BelongsProject: ShiXunDemo
 * @BelongsPackage: com.springbootdemo.shixundemo.Controller
 * @Author: YoungDra
 * @CreateTime: 2024/07/08  19:42
 */
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 *
 */
@RestController
@RequestMapping("email")
public class EmailController {

    @Autowired
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;

    @RequestMapping("sendEmail")
    public String sendSimpleMail(@RequestParam(value = "emailReceiver") String emailReceiver, HttpServletRequest request ) {
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件发送者
        message.setFrom(from);
        // 设置邮件接收者
        message.setTo(emailReceiver+"@qq.com");
        // 设置邮件的主题
        message.setSubject("登录验证码");
        // 设置邮件的正文
        Random random = new Random();
        String code = new String();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10);
            code+=r;
        }
        String text = "您的验证码为：" + code + ",请勿泄露给他人。";
        message.setText(text);
        HttpSession session=request.getSession();
        session.setAttribute("validcode",code);
        System.out.print("session:");
        System.out.println(session.getAttribute("validcode"));
        // 发送邮件
        try {
            javaMailSender.send(message);
            return "发送成功";
        } catch (MailException e) {
            e.printStackTrace();
            System.out.println("false");
        }
        System.out.println("good");
        return "发送失败";
    }
}
